package org.damocode.iot.network.tcp.client;

import io.vertx.core.Vertx;
import io.vertx.core.net.NetClient;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.util.Optional;

/**
 * @Description:
 * @Author: zzg
 * @Date: 2022/5/11 14:55
 * @Version: 1.0.0
 */
@Slf4j
public class VertxTcpClientProvider {

    private final Vertx vertx;

    public VertxTcpClientProvider(Vertx vertx) {
        this.vertx = vertx;
    }

    public VertxTcpClient createNetwork(TcpClientProperties properties) {
        VertxTcpClient client = new VertxTcpClient(properties.getId(),false);
        initClient(client, properties);
        return client;
    }

    public void initClient(VertxTcpClient client, TcpClientProperties properties) {
        NetClient netClient = vertx.createNetClient(properties.getOptions());
        client.setClient(netClient);
        client.setKeepAliveTimeoutMs(Optional.ofNullable(properties.getKeepAliveTimeout()).orElse(Duration.ofMinutes(10).toMillis()));
        netClient.connect(properties.getPort(), properties.getHost(), result -> {
            if (result.succeeded()) {
                log.debug("connect tcp [{}:{}] success", properties.getHost(), properties.getPort());
                client.setRecordParser(properties.getParserSupplier().get());
                client.setSocket(result.result());
            } else {
                log.error("connect tcp [{}:{}] error", properties.getHost(), properties.getPort(),result.cause());
            }
        });
    }


}
